package com.jfinal.kit;

import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.Md5Crypt;

import javax.crypto.Mac;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.zip.CRC32;


/**
 * 功能描述
 * 加密常用类
 */
public class CryptKit {

    public static final String key = "hcx4VSb1";

    public static String apr1Crypt(String str) {
        return Md5Crypt.apr1Crypt(str.getBytes(), key).replace("$apr1$", "");
    }

    public static void main(String[] args) throws GeneralSecurityException {
        System.out.println(CryptKit.apr1Crypt("admin"));
        System.out.println(CryptKit.apr1Crypt("xdf"));
        System.out.println(CryptKit.apr1Crypt("admin2"));
        System.out.println(CryptKit.apr1Crypt("admin").length());
        System.out.println(signature("xxxx", "ssss"));
        System.out.println(crc32("com.ss.android.article.news"));
    }

    public static String Sha256(byte[] input) {
        if (input == null) {
            return null;
        }
        MessageDigest m;
        try {
            m = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            System.out.println("SHA-256 algorithm not found\n" + e.getMessage());
            return null;
        }
        m.update(input, 0, input.length);
        return toHexString(m.digest());
    }

    public static String toHexString(byte[] array) {
        String output = "";
        for (byte rawByte : array) {
            // convert to int (avoid sign issues)
            int b = 0xFF & rawByte;
            // if it is a single digit, make sure it have 0 in front (proper
            // padding)
            if (b <= 0xF) {
                output += "0";
            }
            output += Integer.toHexString(b);
        }
        return output;
    }


    public static String signature(String baseString, String secret) throws GeneralSecurityException {
        SecretKey secretKey = new SecretKeySpec(secret.getBytes(), "HmacMD5");
        Mac mac = Mac.getInstance("HmacMD5");
        mac.init(secretKey);
        byte[] hashBytes = mac.doFinal(baseString.getBytes());
        return Hex.encodeHexString(hashBytes);
    }


    public static String cryptPassword(String salt, String password) {
        return Md5Kit.stringMD5(salt + CryptKit.apr1Crypt((password)));
    }


    /**
     * 生成CRC32校验码
     *
     * @param str
     * @return
     */
    public static Long crc32(String str) {
        if (StrKit.isBlank(str)) {
            return 0L;
        }
        CRC32 crc32 = new CRC32();
        crc32.update(str.getBytes());
        return crc32.getValue();
    }

}
